package com.wunu.smartlock1.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wunu.smartlock1.MainActivity;
import com.wunu.smartlock1.R;
import com.wunu.smartlock1.bluetooth.WunuBlueManager;
import com.wunu.smartlock1.bluetooth.command.BindLockCommand;
import com.wunu.smartlock1.bluetooth.command.CheckBindCommand;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockManageApi;
import com.wunu.smartlock1.net.param.BindLockParam;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.BindLockResult;
import com.wunu.smartlock1.util.CommonUtil;

import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import retrofit2.Call;


/**
 * 扫描搜索到设备后点击绑定
 * Created by admin on 2018/4/21.
 */

public class LockBindActivity extends AppCompatActivity{
    Button bindButton;
    BindLockParam param;

    TextView lockMac;
    TextView lockName;
    TextView lockNote;
    ImageView lockImage;
    Intent intent = new Intent();
    ProgressDialog pd;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            ApiNormalResponse<BindLockResult> resp =(ApiNormalResponse<BindLockResult>) msg.obj;
            System.out.println("code:"+resp.getCode());
            if (resp == null || resp.getCode()!=0 || resp.getData().getCode()!=200){
                Toast.makeText(LockBindActivity.this, "绑定失败:"+resp.getErrorMsg(), Toast.LENGTH_SHORT).show();
                pd.dismiss();
                return;
            }
            pd.dismiss();
            //返回的结果: BindLockBean{lockId=78, managerId=90}
            Toast.makeText(LockBindActivity.this, resp.getData().getMsg(), Toast.LENGTH_SHORT).show();
            startActivity(intent.setClass(LockBindActivity.this, MainActivity.class));
        }
    };
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //构建一个下载进度条
        pd= ProgressDialog.show(LockBindActivity.this, "请等待", "正在检查该锁是否被绑定…");
        new MyTask().execute();
        setContentView(R.layout.smartlock_activity_bindlock);
        bindButton = findViewById(R.id.bindButton);
        lockMac = findViewById(R.id.lockMac);
        lockName = findViewById(R.id.lockName);
        lockNote = findViewById(R.id.lockNote);
        lockImage = findViewById(R.id.lockImage);

        //初始化
        lockMac.setText(" ");
        lockName.setText("悟牛智能锁演示");
        lockNote.setText("申请公告");

       bindButton.setOnClickListener(new View.OnClickListener() {
           //int baseCode = 648845;
           int baseCode = CommonUtil.createBaseCode();
           int openId = 0;
           @Override
           public void onClick(View v) {
               System.out.println("点击了绑定按钮:");
               pd.dismiss();
               pd= ProgressDialog.show(LockBindActivity.this, "请等待", "正在绑定该锁…");
               param = new BindLockParam.Builder()
                       .setBasecode(baseCode)
                       .setLockModel(1)//锁类型
                       .setLockMac(lockMac.getText().toString())//DF:ED:67:87:01:32
                       .setLockName(lockName.getText().toString())
                       .setLockNote(lockNote.getText().toString())//锁申请公告
                       .setLockImageUrl("lock_3.png")//./../../images/lock_3.png
                       .build();
                System.out.println("lockparam : "+param);
               //开线程加载数据
               new Thread() {
                   @Override
                   public void run() {
                       super.run();

                       System.out.println("-------------------------->blcmd begin");
                       try{
                           // 第一步，网络请求预绑锁，获取managerId
                           final LockManageApi service = NetComponent.getRetrofit().create(LockManageApi.class);
                           Call<ApiNormalResponse<BindLockResult>> call = service.bindLock(param);
                           final ApiNormalResponse<BindLockResult> resp = call.execute().body();
                           System.out.println("resp: "+resp);
                           BindLockResult result = resp.getData().getData();
                           openId = result.getManagerId();
                           // 第二步，蓝牙绑锁
                           BindLockCommand blcmd = new BindLockCommand(baseCode,openId);
                           WunuBlueManager manager = WunuBlueManager.Companion.getShared();
                           manager.execute(blcmd, CommonUtil.device, new Function1<Map<String, ? extends Object>, Unit>() {
                               @Override
                               public Unit invoke(Map<String, ?> stringMap) {
                                   if (stringMap.isEmpty()) {
                                       return null;
                                   }
                                   // 判断锁是否绑定成功
                                   Message msg = handler.obtainMessage();
//                           msg.obj = stringMap;
                                   msg.obj = resp;
                                   handler.sendMessage(msg);
                                   return null;
                               }
                           });
                       } catch (Exception e) {
                           System.out.println("锁绑定异常:" + e);
                       }
                   }
               }.start();
           }
       });
    }

    /**
     * 指定设备进行蓝牙异步交互，获取蓝牙信息
     */
    private class MyTask extends AsyncTask {
        //后台线程执行时
        @Override
        protected Object doInBackground(Object... params) {
            System.out.println("蓝牙名称:"+ CommonUtil.device.getName()+"\tmac:"+CommonUtil.device.getMac());
            CheckBindCommand cmd = new CheckBindCommand();
            WunuBlueManager manager = WunuBlueManager.Companion.getShared();
            manager.setCommand(cmd);
            manager.connectDevice(CommonUtil.device);

            System.out.println("map:"+CommonUtil.map);
            while (CommonUtil.map == null) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }
            return null;
        }

        //后台线程执行结束后的操作，其中参数result为doInBackground返回的结果
        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            System.out.println("msg----------task------------->:"+CommonUtil.map);

            System.out.println(CommonUtil.map);
            if(!CommonUtil.map.containsKey("state")){
                pd.dismiss();
                Toast.makeText(LockBindActivity.this, "未获取到蓝牙绑定状态!", Toast.LENGTH_SHORT).show();
                CommonUtil.map = null;
                LockBindActivity.this.finish();
                return;
            }

            if((boolean)CommonUtil.map.get("state")){
                pd.dismiss();
                Toast.makeText(LockBindActivity.this, "该锁已被绑定", Toast.LENGTH_SHORT).show();
                CommonUtil.map = null;
                LockBindActivity.this.finish();
                return;
            }



            String mac = (String)CommonUtil.map.get("mac");
            System.out.println("mac:"+mac);
            lockMac.setText(mac);
            System.out.println("msg-----------------end->:"+CommonUtil.map);
            CommonUtil.map = null;
            System.out.println("order map :"+CommonUtil.map);
            pd.dismiss();
        }
    }
}
